package com.base.terminal.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.base.common.enums.AppType;
import com.base.common.persistent.dao.TerminalMapper;
import com.base.common.persistent.model.Terminal;
import com.base.common.utils.EasyUtil;
import com.base.terminal.service.TerminalService;

@Service("terminalService")
public class TerminalServiceImpl implements TerminalService{
	
	@Resource
	private TerminalMapper terminalMapper;
	
	@Resource
	private EasyUtil easyUtil;

	@Override
	public int updateCode(String code, String phone, int bid) {
		List<Terminal> terminals = new ArrayList<Terminal>();
		
		// 电话号码解密
		if(bid == 0 || bid == 1) {
			phone = EasyUtil.rc4(phone, "szcjy").trim();
		}
		
		// 判断登录设备
		if (bid == 0 || bid == 3) {
			terminals = terminalMapper.queryTerminalByPhoneRegisted(phone, AppType.CJY.getValue());
		} else if(bid == 1 || bid == 4) {
			terminals = terminalMapper.queryTerminalByPhoneRegisted(phone, AppType.YGJ.getValue());
		}
		
		if(terminals.size() > 0){
//			for(Terminal terminal : terminals){
				Terminal t = new Terminal();
				t.setId(terminals.get(0).getId());
				t.setStatus(-1);
				if(bid == 0 || bid == 1) {
					t.setCode(code);
				} else if(bid == 3 || bid == 4) {
					t.setAppleId(code);
				}
				if(terminalMapper.updateTerminalById(t) > 0) {
					return 1;
				};
//			}
		}
		return 0;		
		
	}

	@Override
	public int getCaptcha(String phone, int bid) {
		if(bid == 0 || bid == 1) {
			phone = EasyUtil.rc4(phone, "szcjy").trim();
		}
		int captcha = getSixCaptcha(); // 验证码生成
		easyUtil.sendSms("验证码：" + captcha, phone.trim());
		return captcha;
	}
	
	/**
	 * 获取六位数的验证码
	 * 
	 * @return
	 */
	public int getSixCaptcha() {
		Random rand = new Random();
		int captcha = Math.abs(rand.nextInt()) % (999999 - 100000 + 1) + 100000;
		return captcha;
	}
	
}
